package com.snut.tomorrowNews.controller.back;

import com.snut.tomorrowNews.common.CommonResult;
import com.snut.tomorrowNews.model.Admin;
import com.snut.tomorrowNews.service.back.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;


@RestController
@RequestMapping(path = "/adminLogin")
public class LoginController {

    @Autowired
    LoginService loginService;

    /*
      登录处理方法
     */
     /* @ResponseBody
      @PostMapping(path = "/login")
      public Admin login(Admin admin, HttpServletResponse response){
        Admin admin1 =    loginService.login(admin);
          System.out.println(admin1);
          return admin1;
      }*/

    /*
       向ajax请求响应数据,
       springmvc添加@ResponseBody后,将return的对象直接转为json(添加jar包)
       后端向前端响应数据时,统一数据格式,封装CommonResult类,封装响应结果 code msg data
     */

    @PostMapping(path = "/login")
    public CommonResult login(Admin admin, HttpSession session){
        CommonResult commonResult = null;
        try {
            Admin admin1 =    loginService.login(admin);
            if(admin1==null){
                commonResult = new CommonResult<Admin>(201,"账号或密码错误" , null);
            }else{
                session.setAttribute("admin",admin1);
                commonResult = new CommonResult<Admin>(200,"登录成功" , admin1);
            }
        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult<Admin>(500,"登录失败" , null);
        }
        return commonResult;
    }

    /*
       退出
     */
    @GetMapping(path = "/loginOut")
    public void loginOut(HttpSession session){
           session.invalidate();
    }
}
